#define ROWS 4
#define COLS 4
#define KEY_INTR 1
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
//char hexaKeys[ROWS][COLS] = {
//  {'7','8','9','/'},
//  {'4','5','6','*'},
//  {'1','2','3','-'},
//  {'@','0','=','+'}
//};

void set_row(int val) {
  PORTD = (PORTD & 0x0F) | (val<<4);
}

void scan_row(int row) {
  set_row(1<<row);
}

int get_col(int val) {
  switch (val) {
    case B0001 : return 0;
    case B0010 : return 1;
    case B0100 : return 2;
    case B1000 : return 3;
    default    : return -1;
  }
}

void get_key() {
  int col = -1;
  int row = 0;
  char key = '?';
  delay(10);
  
  //scan col
  for(int row=0;row<ROWS;row++) {
    scan_row(row);
    col = get_col(PINB>>4);
    if(col != -1) {
      key = hexaKeys[row][col];
      break;
    }
  }
  Serial.print("row");
  Serial.println(row);
  Serial.print("col");
  Serial.println(col);
  Serial.println(key);
  //if(key != "?") {Serial.println(key);}
}

void setup(){
  Serial.begin(9600);
  attachInterrupt(INT1,get_key,RISING);
  DDRD = (DDRD & 0x0F) | 0xF0;  //set row output PD4~7
  DDRB =  DDRB & 0xF0;          //set col input  PB0~3

  //PORTD = (PORTD & 0x0F) | 0xF0; //set row all 1 for inttrupt
  set_row(0xF); //set row all 1 for inttrupt
}
   
void loop(){
  delay(1);
}
